﻿// -----------------------------------------------------------------------
// <copyright file="Menu.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Ex04.Menus.Delegates
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public abstract class Menu : MenuItem
    {
        private List<MenuItem> m_SubMenus = new List<MenuItem>();

        public Menu(string i_MenuTitle)
           : base(i_MenuTitle)
        {
        }

        public override void AddMenuItem(MenuItem i_MenuName)
        {
            this.m_SubMenus.Add(i_MenuName);
        }

        public void Show()
        {
            int userChoice = 0;
            bool exitWasChosen = false;
            const bool v_ExitPressed = true;

            while(!exitWasChosen)
            {
                System.Console.Clear();
                System.Console.WriteLine("---------- {0} --------------", this.Title);
                for (int i = 0; i < this.m_SubMenus.Count; i++)
                {
                    System.Console.WriteLine("{0}. {1}", i, this.m_SubMenus[i].Title);                
                }

                try
                {
                    userChoice = this.GetUserSelection();
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Console.WriteLine("Press any key to continue");
                    System.Console.ReadLine();
                    this.Show();
                }

                if (userChoice == 0)
                {
                    exitWasChosen = v_ExitPressed;
                }
                else
                {
                    this.m_SubMenus[userChoice].Invoke();
                }
            }
        }

        private int GetUserSelection()
        {
            int userChoise;
            System.Console.WriteLine("Please choose an option: ");
            userChoise = int.Parse(System.Console.ReadLine());
            if (userChoise < 0 || userChoise >= this.m_SubMenus.Count)
            {
                throw new Exception("invalid choise, please try again");
            }
            else
            {
                return userChoise;
            }
        }

        public Menu this[int i]
        {
            get
            {
                return this.m_SubMenus[i] as Menu;
            }

            set
            {
                this.m_SubMenus[i] = value;
            }
        }

        public override void Invoke()
        {
            this.Show();
        }
    }
}
